#include <jni.h>
#include <android/log.h>

#include "haptimap_android_jni.h"
#include "common.h"

JavaVM *vm;

/* We only use JNI_OnLoad() to set a global pointer to the Java VM that
 * can then be used by multiple instances of the toolkit (if necessary),
 * when creating threads that need to interface with Java.
 * Not sure how important the version number returned is. */
jint JNI_OnLoad(JavaVM *dalvik_vm, void *reserved)
{
    vm = dalvik_vm;

    return JNI_VERSION_1_4;
}

/* Callback wrapper for use with toolkit functions that require a callback to
 * be provided. This calls the callback() method in a user-provided class that
 * implements the "HaptiMapCallbackType" interface - which itself is defined
 * within the main HaptiMap wrapper class. */
void hm_jni_callback_wrapper(void *arg)
{
    JNIEnv *env;
    jobject cb_interface = arg;

    GET_JNI_ENV(&env);

    (*env)->CallVoidMethod(env, cb_interface,
                           (*env)->GetMethodID(env, (*env)->GetObjectClass(env, cb_interface), 
                                               "callback", "()V"));
    return;
}

void hm_jni_save_long(jobject ctx, char *key, long value) {
	JNIEnv *env;
	GET_JNI_ENV(&env);

	jclass hm_class = (*env)->FindClass(env, "org/haptimap/ToolkitService");

	(*env)->CallStaticVoidMethod(env, hm_class,
		(*env)->GetStaticMethodID(env, hm_class, "JNISaveLong", "(Landroid/content/Context;Ljava/lang/String;J)V"),
		ctx, (*env)->NewStringUTF(env, key), (jlong)value);
}

long hm_jni_get_long(jobject ctx, char *key) {
	JNIEnv *env;
	GET_JNI_ENV(&env);

	jclass hm_class = (*env)->FindClass(env, "org/haptimap/ToolkitService");
	jlong value = -1;

	value = (*env)->CallStaticLongMethod(env, hm_class,
		(*env)->GetStaticMethodID(env, hm_class, "JNIGetLong", "(Landroid/content/Context;Ljava/lang/String;)J"),
		ctx, (*env)->NewStringUTF(env, key));

	return (long)value;
}
